// weather.js: 获取天气信息的程序

// 引入必要的模块
const https = require('https');

// 定义高德API的URL和参数
function getWeather(apiKey, location) {
    const amapWeatherUrl = `https://restapi.amap.com/v3/weather/weatherInfo?key=${apiKey}&city=${location}`;

    // 发送HTTPS请求以获取天气信息
    return new Promise((resolve, reject) => {
        https.get(amapWeatherUrl, (res) => {
            let data = '';

            // 监听数据接收事件
            res.on('data', (chunk) => {
                data += chunk;
            });

            // 监听请求结束事件
            res.on('end', () => {
                try {
                    const weatherData = JSON.parse(data);
                    if (weatherData.status === '1') {
                        resolve(weatherData);
                    } else {
                        reject(new Error(`Error fetching weather data: ${weatherData.info}`));
                    }
                } catch (e) {
                    reject(new Error('Invalid response from server'));
                }
            });
        }).on('error', (err) => {
            reject(err);
        });
    });
}

module.exports = { getWeather };
